package org.gwt.grin.rebind.input;

import java.util.Formatter;

import org.gwt.grin.client.input.CommandRCHandler;
import org.gwt.grin.rebind.AbstractSENode;
import org.gwt.grin.rebind.SECommand;
import org.gwt.grin.rebind.SENode;
import org.gwt.grin.rebind.ShowBuilder;

import com.google.gwt.uibinder.rebind.IndentedWriter;

public class SECommandRCHandler extends AbstractSENode implements SENode,
		SERCHandler {

	private final int mask;
	private final boolean wantKeypress;
	private final SECommand[] commands;

	public SECommandRCHandler(String name, int mask, boolean wantKeypress,
			SECommand[] commands) {
		super(name);
		this.mask = mask;
		this.wantKeypress = wantKeypress;
		this.commands = commands;
	}

	@Override
	public String write(ShowBuilder builder) {
		String cn = getClassName();
		Formatter formatter = new Formatter();
		formatter
				.format("new %s(\"%s\", %d, %b)", cn, name, mask, wantKeypress);
		return formatter.toString();
	}

	@Override
	public void setup(IndentedWriter w, ShowBuilder builder) {
		String vn = getVN(builder);
		w.write("%s.setup(%s);", vn, makeCommandsArray(builder, commands));
	}

	@Override
	public int getKeyPressedInterestMask(SERCHandler h) {
		if (wantKeypress) {
			return mask;
		} else {
			return 0;
		}
	}

	@Override
	public int getKeyReleasedInterestMask(SERCHandler h) {
		if (wantKeypress) {
			return 0;
		} else {
			return mask;
		}
	}

	@Override
	protected String getClassName() {
		return CommandRCHandler.class.getName();
	}

}
